const path = require('path');
const FiberPlugin = require('./config/plugins/FiberPlugin');
const IconfontPlugin = require('@fiber/iconfont-webpack-plugin');
const I18nWebpackPlugin = require('@fiber/i18n-webpack-plugin');
const VueStyleInlinePlugin = require('@fiber/vue-style-inline-webpack-plugin');
const FiberSourceMapPlugin = require('@fiber/sourcemap-webpack-plugin');
const { cap, platformCommon, vPortal, vPortalLine } = require('./config/icons');
// js与 html
const outputDir = 'dist/';
// const outputDir = 'dist/webapps/static/collaboration/';
const isProd = process.env.NODE_ENV === 'production';
const externals = {
  fiber: 'window.Fiber',
  vue: 'window.Vue',
  axios: 'window.axios',
  moment: 'window.moment'
};

console.log(process.env.NODE_ENV, process.env.SERVER_URL);
process.env.BROWSERSLIST_DANGEROUS_EXTEND = 1;

// 配置反向代理
const proxy = {
  '/seeyon': {
    // 匹配所有以 ‘/seeyon’ 开头的请求路径
    target: process.env.SERVER_URL,
    changeOrigin: true,
    pathRewrite: { '^/seeyon': '/seeyon' },
    onProxyReq(req) {
      const url = new URL(process.env.SERVER_URL);
      req.setHeader('Host', url.host);
      req.setHeader('Origin', url.host);
      req.setHeader('Referer', process.env.SERVER_URL);
      // 防止nginx反向代理验证ip
      req.removeHeader('x-forwarded-for');
      req.removeHeader('x-forwarded-port');
      req.removeHeader('x-forwarded-host');
    },
    onProxyRes(res, rawRes) {
      const { statusCode, headers } = res;
      const { location } = headers;
      if (/^30[12]$/.test(String(statusCode)) && /:\/\//.test(location)) {
        const url = new URL(location);
        url.host = rawRes.headers.host;
        headers.location = url.href;
      }
    }
  },
  '/static/': {
    target: process.env.SERVER_URL
  },
  '/sportal/': {
    target: process.env.SERVER_URL
  }
};
//接口代理
proxy[process.env.VUE_APP_API] = {
  target: process.env.API_SERVER_URL || process.env.SERVER_URL
};

//把版本存到一个对象里面
const versionData = { version: new Date().toLocaleString() };

const plugins = [
  new FiberPlugin(versionData),
  new FiberSourceMapPlugin(),
  new I18nWebpackPlugin({ inject: false }),
  new VueStyleInlinePlugin({ test: /css-loader/ }),
  new IconfontPlugin({
    downloadFile: isProd,
    projects: [
      { name: 'cap', id: 385729, icons: cap },
      { name: 'platform-common', id: 883584, icons: platformCommon },
      { name: 'v-portal', id: 532864, icons: vPortal },
      { name: 'v-portal-line', id: 532862, icons: vPortalLine }
    ]
  })
];
const assetsDir = 'static/app/collaboration';
const assetHash = isProd ? '?[contenthash:5]' : '';

module.exports = {
  outputDir: isProd ? outputDir : 'dist/',
  publicPath: isProd ? '/' : '/',
  indexPath: 'seeyon/app/collaboration/index.html',
  assetsDir,
  pages: { index: 'src/main.js' },
  lintOnSave: true,
  configureWebpack: {
    externals,
    plugins,
    output: {
      // js打包后，要保证文件名一致，并且不能有缓存问题
      filename: `${assetsDir}/js/[name].min.js${assetHash}`,
      chunkFilename: `${assetsDir}/js/[name].min.js${assetHash}`
    },
    resolve: {
      alias: { xdesign: path.resolve(__dirname, 'src/layout/xdesign') }
    }
  },
  chainWebpack: (config) => {
    // 修复vue-cli无法转换.cjs
    config.module.rule('js').test(/\.[cm]?jsx?$/);
    // 移除 prefetch/preload 插件
    config.plugins.delete('preload-index');
    config.plugins.delete('prefetch-index');
  },
  productionSourceMap: false,
  transpileDependencies: [
    /[/\\]node_modules[/\\](.+?)?devtools-api[/\\]/,
    /[/\\]node_modules[/\\]pinia[/\\]/,
    /[/\\]node_modules[/\\]@tiptap[/\\]/,
    // vue-demi | vue-color | vue-ts-types
    /[/\\]node_modules[/\\]vue-[-\w]+[/\\]/,
    // see @tiptap/pm/package.json dependencies
    /[/\\]node_modules[/\\]prosemirror-[-\w]+[/\\]/,
    // hmr debugging
    /[/\\]node_modules[/\\]sockjs-client[/\\]/
  ],
  css: {
    loaderOptions: {
      // 给 sass-loader 传递选项
      sass: {
        additionalData: `@import "~@/assets/css/_variables.scss";`
      }
    }
  },
  devServer: {
    port: 7000,
    open: true,
    disableHostCheck: true,
    historyApiFallback: true,
    proxy
  }
};
